using System;
using System.Collections;
using UnityEngine;

namespace EventBehaviorTree
{
    [Serializable]
    public class Sentinel : EventNode
    {
        private AsyncWorker _asyncWorker;
        private Func<bool> Condition;
        private NodeMsg _conditionMsg;//[TODO]

        public Sentinel(Func<bool> condition, NodeMsg conditionMsg)
        {
            SetCondition(condition);
            _conditionMsg = conditionMsg;
        }
        public Sentinel(Func<bool> condition) : this(condition, NodeMsg.Succeed) { }

        public void SetCondition(Func<bool> condition)
        {
            Condition = condition == null ? delegate { return true; } : condition;
        }

        public override void SetCoroutineStarter(MonoBehaviour coroutineStarter)
        {
            _asyncWorker = new AsyncWorker(coroutineStarter);
        }

        private IEnumerator Worker()
        {
            yield return new WaitUntil(Condition);
            SuperiorNodeEvent(_conditionMsg);
        }

        public override void NodeEvent(NodeMsg nodeMessage)
        {
            switch (nodeMessage)
            {
                case NodeMsg.Start:
                    if (!_isWorking)
                    {
                        _isWorking = true;
                        _asyncWorker.ResetWorker(Worker());
                        _asyncWorker.Start();
                    }
                    break;
                case NodeMsg.CMD_Stop:
                    if (_isWorking)
                    {
                        _asyncWorker.ResetWorker(Worker());
                        _isWorking = false;
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
